package com.example.springbootexp03demo.services;

import com.example.springbootexp03demo.models.StatData;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;


@Service
public class CrawlVirusData implements InitializingBean {

    //    private static final String VIRUS_DATA_URL = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    private static final String VIRUS_DATA_URL = "https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    // 用于存放爬取到的每一条数据
    private final List<StatData> allStats = new ArrayList<>();

    public List<StatData> getAllStats() {
        return allStats;
    }

    // 疫情csv文件数据的爬取以及csv文件的解析
    @Scheduled(cron = "${statData.update}")
    public void fetchCoronaVirusData() throws IOException {

        // 从相关的url爬取csv文件数据
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(VIRUS_DATA_URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        /*
         * InputStream inputStream = body.getInputStream();
         * InputStreamReader reader = new InputStreamReader(inputStream);
         * Reader input = new BufferedReader(reader);
         * 浓缩精华
         */
        Reader input = new InputStreamReader(body.getInputStream(), "UTF-8");

        /**
         * 相关链接 http://commons.apache.org/proper/commons-csv/apidocs/org/apache/commons/csv/CSVFormat.html
         * withFirstRecordAsHeader() 使用第一个记录作为 ^标题^ 返回一个新值
         * parse() 解析相关内容
         */
        Iterable<CSVRecord> records = CSVFormat.DEFAULT
                .withFirstRecordAsHeader()
                .parse(input);

        // 解析csv文件
        for (CSVRecord record : records) {
//            String province = record.get(0);
            String province = record.get("Province/State");
//            String country = record.get(1);
            String country = record.get("Country/Region");
            int latest = Integer.parseInt(record.get(record.size() - 1));
            int diff = Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2));
            StatData statData = new StatData(province, country, latest, diff);
            allStats.add(statData);
        }
    }

    // 重写afterPropertiesSet方法以达到在初始化Bean的过程中 主动调用fetchCoronaVirusData方法来爬取一次数据
    @Override
    public void afterPropertiesSet() throws Exception {
        fetchCoronaVirusData();
    }
}
